# /bin/bash

function partition::init()
{
    partition_ops=""
    partition_primary=1
}

# partition::append TYPE NAME SIZE
# TYPE: PRIMARY / EXTENSION / LOGICAL
# SIZE: size{K,M,G,T,P} / REST
function partition::append()
{
    local size="$3"
    if [ "$size" == "REST" ] || [ "$1" == "EXTENSION" ]; then
        size=""
    else
        size="+${size}"
    fi

    partition_ops="${partition_ops}n\n"
    case "$1" in
        PRIMARY) partition_ops="${partition_ops}p\n$((partition_primary++))\n" ;;
        EXTENSION) partition_ops="${partition_ops}e\n" ;;
        LOGICAL) ;;
    esac

    partition_ops="${partition_ops}\n${size}\n"
}

# partition::do TYPE DEVICE
# TYPE: GPT, GPT_IRIX, DOS, SUN
function partition::do()
{
    case "$1" in
        DOS) partition_ops="o\n${partition_ops}" ;;
        GPT) partition_ops="g\n${partition_ops}" ;;
        SUN) partition_ops="s\n${partition_ops}" ;;
        GPT_IRIX) partition_ops="G\n${partition_ops}" ;;
    esac
    echo -en "g\nw\n" | fdisk "$2"
    echo -en "${partition_ops}w\n" | fdisk "$2"
}

function file::mirrorlist()
{
cat << EOF
################################################################################
################# Arch Linux mirrorlist generated by Reflector #################
################################################################################

# With:       reflector --sort rate --threads 100 -c China --save /etc/pacman.d/mirrorlist
# When:       2023-02-07 16:02:22 UTC
# From:       https://archlinux.org/mirrors/status/json/
# Retrieved:  2023-02-07 16:02:16 UTC
# Last Check: 2023-02-07 15:55:40 UTC

Server = http://mirrors.ustc.edu.cn/archlinux/\$repo/os/\$arch
Server = https://mirrors.sjtug.sjtu.edu.cn/archlinux/\$repo/os/\$arch
Server = https://mirrors.xjtu.edu.cn/archlinux/\$repo/os/\$arch
Server = rsync://mirrors.bfsu.edu.cn/archlinux/\$repo/os/\$arch
Server = http://mirrors.aliyun.com/archlinux/\$repo/os/\$arch
Server = https://mirrors.aliyun.com/archlinux/\$repo/os/\$arch
Server = http://mirrors.shanghaitech.edu.cn/archlinux/\$repo/os/\$arch
Server = https://mirrors.shanghaitech.edu.cn/archlinux/\$repo/os/\$arch
EOF
}

function file::hosts()
{
cat << EOF
127.0.0.1 localhost
::1       localhost
EOF
}

function file::xinitrc()
{
cat << EOF
userresources=\$HOME/.Xresources
usermodmap=\$HOME/.Xmodmap
sysresources=/etc/X11/xinit/.Xresources
sysmodmap=/etc/X11/xinit/.Xmodmap

# merge in defaults and keymaps

if [ -f \$sysresources ]; then
    xrdb -merge \$sysresources
fi

if [ -f \$sysmodmap ]; then
    xmodmap \$sysmodmap
fi

if [ -f "\$userresources" ]; then
    xrdb -merge "\$userresources"
fi

if [ -f "\$usermodmap" ]; then
    xmodmap "\$usermodmap"
fi

# start some nice programs

if [ -d /etc/X11/xinit/xinitrc.d ] ; then
    for f in /etc/X11/xinit/xinitrc.d/?*.sh ; do
        [ -x "\$f" ] && source "\$f"
    done
    unset f
fi

#twm &
#xclock -geometry 50x50-1+1 &
#xterm -geometry 80x50+494+51 &
#xterm -geometry 80x20+494-0 &
#exec xterm -geometry 80x66+0+0 -name login
source \$HOME/.xprofile
exec i3
EOF
}

function file::override_conf()
{
cat << EOF
[Service]
ExecStart=
ExecStart=-/bin/agetty -a luwh --noclear %I \$TERM
EOF
}

function partition()
{
    if [ -e mnt ]; then
        umount mnt/boot
        umount mnt
        rm -rf mnt
    fi

    timedatectl set-ntp true
    sed -i 's@^#Color$@Color@g' /etc/pacman.conf
    sed -i 's@^SigLevel .*@SigLevel = Never@g' /etc/pacman.conf
    file::mirrorlist > /etc/pacman.d/mirrorlist

    partition::init
    partition::append PRIMARY BOOT 512M
    partition::append PRIMARY MAIN REST
    partition::do GPT /dev/sda

    yes | mkfs.fat -F32 -n BOOT /dev/sda1
    yes | mkfs.ext4     -L MAIN /dev/sda2
    mkdir -p mnt
    mount /dev/sda2 mnt
    mkdir -p mnt/boot
    mount /dev/sda1 mnt/boot
}

function setupbase()
{
    pacstrap -P mnt base linux linux-firmware dhcpcd
    genfstab -U mnt >> mnt/etc/fstab
    arch-chroot mnt ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
    arch-chroot mnt hwclock --systohc
    arch-chroot mnt systemctl enable dhcpcd
    sed -i '$a nohook resolv.conf' mnt/etc/dhcpcd.conf
    sed -i 's@^#\(en_US.UTF-8\)@\1@g' mnt/etc/locale.gen
    sed -i 's@^#\(zh_CN.UTF-8\)@\1@g' mnt/etc/locale.gen
    arch-chroot mnt locale-gen
    echo LANG=en_US.UTF-8 > mnt/etc/locale.conf
    echo archlinux > mnt/etc/hostname
    file::hosts > mnt/etc/hosts
    echo -en "root@archlinux\nroot@archlinux\n" | arch-chroot mnt passwd root
}

function setupboot()
{
    mkdir mnt/boot/grub
    arch-chroot mnt pacman -Syyu --noconfirm
    arch-chroot mnt pacman -S --noconfirm grub efibootmgr intel-ucode os-prober
    arch-chroot mnt bash -c "grub-mkconfig > /boot/grub/grub.cfg"
    arch-chroot mnt grub-install --target=x86_64-efi --efi-directory=/boot
}

function setupxorg()
{
    arch-chroot mnt pacman -S --noconfirm xorg xorg-xinit i3-wm i3lock
    mkdir -p mnt/home/luwh
    mkdir -p mnt/etc/systemd/system/getty@tty1.service.d
    file::xinitrc > mnt/home/luwh/.xinitrc
    file::override_conf > mnt/etc/systemd/system/getty@tty1.service.d/override.conf
}

function setupluwh()
{
    # user
    arch-chroot mnt useradd -mG wheel luwh
    echo -en "luwh@archlinux\nluwh@archlinux\n" | arch-chroot mnt passwd luwh
    sed -i 's@^# \(%wheel.*NOPASSWD\)@\1@g' mnt/etc/sudoers
    sed -i 's@^\(luwh:.*\)/bin/bash@\1/usr/bin/zsh@g' mnt/etc/passwd

    # config
    arch-chroot mnt pacman -S --noconfirm git neovim vi man base-devel wget zsh
    arch-chroot mnt su luwh -c "sudo chown luwh:luwh -R ~"
    arch-chroot mnt su luwh -c "mkdir -p ~/{repos,.config,.ssh}"
    arch-chroot mnt su luwh -c "git clone --recursive https://gitee.com/karl1864/srepo ~/repos/srepo"
    arch-chroot mnt su luwh -c "wget https://gitee.com/karl1864/config/raw/master/srepo.yml -O ~/srepo.yml"
    arch-chroot mnt su luwh -c "bash ~/repos/srepo/install_yaml.sh"
    arch-chroot mnt su luwh -c "~/repos/srepo/srepo init ~/srepo.yml"
    arch-chroot mnt su luwh -c "cd; ~/my/shell/generate_from_default.sh"

    # package
    arch-chroot mnt pacman -S --noconfirm ack alacritty alsa-utils bat bison ccls \
        chromium cmake deepin-screenshot fcitx5-im fcitx5-chinese-addons \
        feh flex fzf gdb git-lfs glfw-x11 glu gn go htop i3blocks i3-gaps i3status \
        lazygit make mplayer ncdu net-tools ninja nodejs npm polybar ranger rofi \
        openssh the_silver_searcher tig ttf-droid variety xclip xcompmgr yarn

    # vmware
    arch-chroot mnt pacman -S --noconfirm open-vm-tools gtkmm3 gtkmm gtk2 xf86-video-vmware
    arch-chroot mnt systemctl enable vmtoolsd
    sed -i 's@^MODULES=(@MODULES=(vsock vmw_vsock_vmci_transport vmw_balloon vmw_vmci vmwgfx @g' mnt/etc/mkinitcpio.conf
    arch-chroot mnt mkinitcpio -p linux
    mkdir -p mnt/mnt/hgfs

    # docker
    arch-chroot mnt pacman -S --noconfirm docker
    mkdir -p mnt/etc/docker
    arch-chroot mnt systemctl enable docker
    arch-chroot mnt usermod -aG docker luwh

    # swap
    arch-chroot mnt dd if=/dev/zero of=swapfile bs=1G count=8
    arch-chroot mnt mkswap swapfile
    arch-chroot mnt chmod 0600 swapfile
    sed -i '$a /swapfile swap swap defaults 0 0' mnt/etc/fstab
}

function main()
{
    set -ex
    partition "$@"
    setupbase "$@"
    setupboot "$@"
    setupxorg "$@"
    setupluwh "$@"
    reboot
}

main "$@"
